/*
 * Copyright 2020-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sagacity.framework.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.sun.jndi.toolkit.url.UrlUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Excel工具类
 * @author xingyun
 * @date 2020-07-04 15:03
 */
@Slf4j
public final class ExcelUtils {

    public static <T> void exportExcel(List<T> tList){
        HttpServletResponse response = RequestUtil.getResponse();
//        // 设置 Excel 响应头
        setExcelResponseHeaders(response);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            log.warn("[ExcelUtils#exportExcel] excel 导出异常",e);
        }

//        File file = new File("F:\\data\\test."+getExcelType().toLowerCase());
//        ExcelWriterBuilder write = EasyExcel.write(file);

        ExcelWriterBuilder write = EasyExcel.write(outputStream);
        write.excelType(ExcelTypeEnum.valueOf(getExcelType()));
        // 传入标题头
        String headerAliasStr = RequestUtil.getHeader("headerAlias");
        if (StringUtil.isNotBlank(headerAliasStr)) {
            try {
                headerAliasStr = UrlUtil.decode(headerAliasStr, "UTF-8");
            } catch (MalformedURLException | UnsupportedEncodingException e) {
                log.warn("decode headerAlias:{} error",headerAliasStr);
            }
            List<List<String>> headList = new ArrayList<>();
            for (String headerName : StringUtil.split(headerAliasStr, ",")) {
                headList.add(Collections.singletonList(headerName));
            }
            if (CollectionUtil.isNotEmpty(headList)) {
                write.head(headList);

                // 没有传入用类注解
            } else {
                write.head(tList.get(0).getClass());
            }

            // 没有传入用类注解
        } else {
            write.head(tList.get(0).getClass());
        }
//        write.includeColumnFieldNames()
//        write.sheet("");
        write.sheet().doWrite(tList);
    }


    private static void setExcelResponseHeaders(HttpServletResponse response){
        String excelType = getExcelType();
        if(ExcelTypeEnum.XLSX.name().equals(excelType) || ExcelTypeEnum.XLS.name().equals(excelType)){
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        }else if(ExcelTypeEnum.CSV.name().equals(excelType.toLowerCase())){
            response.setContentType("application/csv;charset=UTF-8");
        }
        ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.valueOf(excelType);
        String fileName = StringUtil.defaultString(RequestUtil.getHeader("fileName"), IdClient.nextIdStr() +excelTypeEnum.getValue());
        // 下面几行是为了解决文件名乱码的问题
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
    }

    private static String getExcelType() {
        return StringUtil.defaultString(RequestUtil.getHeader("excelType"), "XLSX").toUpperCase();
    }

}
